<template>
  <div>
    <TopBar :title="attr | titleInfo" bgc="background: #F3F3F3;"></TopBar>

    <van-field style="line-height: 6vh;" size="large" :label="attr | attrInfo" v-model="editInfo">
      <van-button
        slot="button"
        type="primary"
        style="height: 6vh;"
        :disabled="userInfo[this.attr] === editInfo  || editInfo === ''"
        @click="updateUser"
      >保存</van-button>
    </van-field>
  </div>
</template>

<script>
import { mapState } from "vuex";
import TopBar from "@/views/component/topBar";
export default {
  components: {
    TopBar
  },
  data() {
    return {
      editInfo: "",
      attr: this.$route.params.attr
    };
  },
  mounted() {
    this.editInfo = this.userInfo[this.attr];
  },
  filters: {
    //过滤器的配置项
    attrInfo: function(attr) {
      if (attr === "username") return "用户名";
      if (attr === "name") return "姓名";
      if (attr === "number") return "学号";
      if (attr === "telephone") return "电话";
      if (attr === "college") return "学院";
    },
    titleInfo: function(attr) {
      if (attr === "username") return "更改用户名";
      if (attr === "name") return "更改姓名";
      if (attr === "number") return "更改学号";
      if (attr === "telephone") return "更改电话";
      if (attr === "college") return "更改学院";
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.userInfo
    })
  },
  methods: {
    updateUser() {
      let userFields = {};
      userFields[this.attr] = this.editInfo;
      this.$api
        .post(`/api/user/edit/${this.userInfo.id}`, userFields)
        .then(res => {
          this.$message({
            type: "success",
            message: res.data.message
          });
          this.$router.go(-1);
        })
        .catch(() => {
          this.$message({
            type: "danger",
            message: "账号已存在，修改失败"
          });
        });
    }
  }
};
</script>

<style lang="less" scoped>
</style>